<template>
    <div class="login-form" v-enter="submitLoginForm">
        <div class="title">登录</div>
        <div class="form">
            <base-form
                :formItems="loginFormItems"
                :formData="loginFormSubmit"
                :formRules="loginFormRule"
                :formConfig="loginFormConfig"
                ref="loginForm"
                @onButtonClick="handelFormButtonClick"
            >
                <template slot="codeImg">
                    <el-form-item>
                        <div class="code-img" @click="handelChangeCodeImg">
                            <el-image :src="codeImgUrl" v-if="!codeLoading" />
                            <span v-else>
                                <span class="el-icon-loading"></span>
                                加载中
                            </span>
                        </div>
                    </el-form-item>
                </template>
            </base-form>
        </div>
    </div>
</template>
<script>
import BaseForm from '@/components/baseForm/index'
import { getCodeImg } from '@/http/apis/index'
import { mapMutations } from 'vuex'
import { getAES, Encrypt, Decrypt } from '@/utils/ase.js'
import Cookies from 'js-cookie'
export default {
    components: {
        BaseForm
    },
    data() {
        return {
            loginFormItems: [
                [
                    {
                        ltype: 'input', // 大类型（input）
                        placeholder: '请输入用户名', // 文字提示
                        prop: 'username', // 绑定的key
                        prefixIcon: 'el-icon-user-solid' // 控件前的图标
                    }
                ],
                [
                    {
                        ltype: 'input', // 大类型（input）
                        type: 'password', // 小类型（input）
                        showPassword: true, // 显示密码
                        placeholder: '请输入密码', // 文字提示
                        prop: 'password', // 绑定的key
                        prefixIcon: 'password', // 控件前的图标
                        width: 'w-1'
                    }
                ],
                [
                    {
                        ltype: 'input', // 大类型（input）
                        placeholder: '请输入验证码', // 文字提示
                        prop: 'code', // 绑定的key
                        width: 'w-2'
                    },
                    {
                        ltype: 'custom', // 大类型（input）
                        slotName: 'codeImg',
                        width: 'w-2'
                    }
                ],
                [
                    {
                        ltype: 'checkbox', // 大类型（input）
                        prop: 'rememberMe', // 绑定的key
                        options: [
                            {
                                label: '记住密码',
                                value: false
                            }
                        ],
                        width: 'w-1'
                    }
                ],
                [
                    {
                        ltype: 'button', // 大类型（input）
                        type: 'primary',
                        text: '登录', // 文字提示
                        prop: 'submitLoginForm', // 绑定的key
                        width: 'w-1',
                        loading: false
                    }
                ]
            ],
            loginFormSubmit: {
                rememberMe: false,
                username: '',
                password: '',
                code: '',
                uuid: ''
            },
            loginFormRule: {
                username: [
                    {
                        required: true,
                        message: '请输入用户名称',
                        trigger: 'blur'
                    }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' }
                ]
            },
            loginFormConfig: {
                size: 'medium', // 表单控件大小
                labelWidth: '100px', // label的宽度
                labelPosition: 'left' // label对齐方式
            },
            codeImgUrl: '',
            codeLoading: false
        }
    },
    directives: {
        enter: {
            bind(el, binding) {
                el.addEventListener('keyup', event => {
                    if (event.keyCode === 13) {
                        binding.value()
                    }
                })
            }
        }
    },
    mounted() {
        this.handelChangeCodeImg()
    },
    methods: {
        ...mapMutations('user', ['SET_UUID']),
        /**
         * 表单按钮点击
         */
        handelFormButtonClick(params) {
            try {
                this[params.prop]()
            } catch (error) {
                throw new Error(error)
            }
        },
        /**
         * 提交表单
         */
        submitLoginForm() {
            this.$refs['loginForm'].submitForm(async res => {
                this.$refs.loginForm.setFormItemProp(
                    'submitLoginForm',
                    'loading',
                    true
                )
                let userInfo = {
                    authType: 'PWD',
                    authParameters: {
                        uuid: res.uuid,
                        authAccount: getAES(res.uuid, res.username.trim()),
                        password: getAES(res.uuid, res.password.trim()),
                        captcha: res.code
                    }
                }
                this.$store
                    .dispatch('Login', userInfo)
                    .then(() => {
                        this.$refs.loginForm.setFormItemProp(
                            'submitLoginForm',
                            'loading',
                            false
                        )
                        this.handelChangeCodeImg()
                        this.setCookie(res)
                        this.$router
                            .push({ path: this.redirect || '/' })
                            .catch(err => {
                                throw new Error(err)
                            })
                    })
                    .catch(() => {
                        this.$refs.loginForm.setFormItemProp(
                            'submitLoginForm',
                            'loading',
                            false
                        )
                        this.handelChangeCodeImg()
                    })
            })
        },
        /**
         * 生成验证码
         */
        async handelChangeCodeImg() {
            this.codeLoading = true
            try {
                let res = await getCodeImg({
                    length: 1
                })
                if (res && res.data && res.code === 0) {
                    this.codeImgUrl = 'data:image/gif;base64,' + res.data.img
                    this.loginFormSubmit.uuid = res.data.uuid
                } else {
                    this.$message.error({
                        message: '获取验证码失败！'
                    })
                }
                this.codeLoading = false
                this.getCookie()
            } catch (error) {
                this.codeLoading = false
            }
        },
        /**
         * 存储密码
         */
        setCookie(res) {
            if (res.rememberMe) {
                Cookies.set('username', res.username, { expires: 30 })
                Cookies.set('password', Encrypt(res.password), { expires: 30 })
                Cookies.set('rememberMe', res.rememberMe, { expires: 30 })
            } else {
                Cookies.remove('username')
                Cookies.remove('password')
                Cookies.remove('rememberMe')
            }
        },
        /**
         * 获取缓存里的数据
         */
        getCookie() {
            const username = Cookies.get('username')
            const password = Cookies.get('password')
            const rememberMe = Cookies.get('rememberMe')
            this.loginFormSubmit.username =
                username === undefined
                    ? this.loginFormSubmit.username
                    : username
            this.loginFormSubmit.password =
                password === undefined
                    ? this.loginFormSubmit.password
                    : Decrypt(password.trim())
            this.loginFormSubmit.rememberMe =
                rememberMe === undefined ? false : Boolean(rememberMe)
            console.log('this.loginFormSubmit', this.loginFormSubmit)
        }
    }
}
</script>
<style lang="scss" scoped>
.login-form {
    @include box_flex(
        $width: 400px,
        $height: auto,
        $direction: column,
        $justify: center,
        $align: center
    );
    @include box_shadow();

    padding: $margin-sm $margin-md;
    @include background_color($color: 'cover');

    border-radius: 4px;
    .title {
        @include box_flex(
            $width: auto,
            $height: auto,
            $direction: row,
            $justify: center,
            $align: center
        );
        // font-weight: bold;
        margin-bottom: 10px;
        padding: 10px 0;
        font-size: 26px;
        letter-spacing: 10px;
    }
    .form {
        @include box_flex(
            $width: 100%,
            $height: auto,
            $direction: column,
            $justify: center,
            $align: center
        );
        .code-img {
            @include box_flex(
                $width: 100%,
                $height: 35px,
                $direction: column,
                $justify: center,
                $align: center
            );
            @include border_color($color: 'border-base');

            border-radius: 4px;
            cursor: pointer;
            img {
                width: 100%;
                height: 100%;
                border: none;
                outline: none;
            }
            img[src=''] {
                opacity: 0;
            }
        }
    }
}
</style>
